package com.example.demo.controller;

import com.example.demo.config.AjaxResult;
import com.example.demo.model.ExpressInfo;
import com.example.demo.model.OrderInfo;
import com.example.demo.model.ProductInfo;
import com.example.demo.model.UserInfo;
import com.example.demo.service.*;
import com.example.demo.util.ConstVariable;
import com.example.demo.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;

import static org.bouncycastle.asn1.cms.CMSObjectIdentifiers.data;


@RestController
@RequestMapping("/order")
public class OrderController {
    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private ExpressService expressService;

    @Autowired
    private ProductService productService;

    @Autowired
    private SellerProductService sellerProductService;



    @PostMapping("/create")
    public AjaxResult createOrder(@RequestBody OrderInfo orderInfo, HttpSession session) {
        try {
            // 从session获取用户信息
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            // 设置买家ID
            orderInfo.setBuyerId(userInfo.getId());
            
            // 检查商品状态
            ProductInfo product = productService.getById(orderInfo.getProductId());
            if (product == null) {
                return AjaxResult.fail("商品不存在");
            }
            if (product.getStatus() != 1) { // 假设1表示商品可购买状态
                return AjaxResult.fail("商品已下架或已售出");
            }
            
            // 创建订单并修改商品状态
            OrderInfo createdOrder = orderService.createOrderWithDetails(orderInfo);
            
            // 更新商品状态为已售出
            product.setStatus(2); // 假设2表示已售出状态
            sellerProductService.updateProduct(product);
            
            return AjaxResult.success(createdOrder);
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return AjaxResult.fail("创建订单失败：" + e.getMessage());
        }
    }

    @PostMapping("/ship")
    public AjaxResult ship(@RequestBody ExpressInfo expressInfo, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            boolean success = orderService.ship(expressInfo, userInfo.getId());
            return success ? AjaxResult.success("发货成功") : AjaxResult.fail("发货失败");
        } catch (Exception e) {
            log.error("发货失败", e);
            return AjaxResult.fail("发货失败");
        }
    }

    @GetMapping("/express-info/{orderNo}")
    public AjaxResult getExpressInfo(@PathVariable String orderNo, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }

            
            // 验证订单是否属于当前用户
            OrderInfo order = orderService.getOrderByOrderNo(orderNo);
            if (order == null) {
                return AjaxResult.fail("订单不存在");
            }
            
            if (order.getBuyerId() == null || !order.getBuyerId().equals(userInfo.getId())) {
                return AjaxResult.fail("无权查看该订单信息");
            }
            
            ExpressInfo info = expressService.getByOrderNo(orderNo);
            if (info == null) {
                return AjaxResult.fail("未找到快递信息");
            }
            
            return AjaxResult.success(info);
        } catch (Exception e) {
            log.error("获取快递信息失败", e);
            return AjaxResult.fail("获取快递信息失败");
        }
    }

}
